'use strict';
const fs = require('fs');
const path = require('path');

// 同步读取上级目录下的所有文件到files中
function readDirectory(pathName, dirs = []) {
  fs.readdirSync(pathName).forEach((item, index) => {
    const stat = fs.lstatSync(path.join(pathName, item));
    if (stat.isDirectory()) {
      readDirectory(path.join(pathName, item), dirs);
    } else if (stat.isFile()) {
      const filePath = path
        .join(pathName, item)
        .replace(path.resolve(__dirname), '')
        .replaceAll('\\', '/')
        .slice(1);
      dirs.push(filePath);
    }
  });
  return dirs;
}
// 读取文件目录
const dir = path.resolve(__dirname + '/routes');
const filePaths = readDirectory(dir);

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.prefix('/api/v1');

  filePaths.forEach(file => {
    if (file === 'index.js') {
      return;
    }
    const router = require(`./${file}`);
    router(app);
  });

  router.get('*', controller.home.index);
};
